#pragma once

#include <iostream>
#include <pthread.h>
#include <string>

class myThread
{
public:
    typedef enum
    {
        NEW = 0,
        RUNNING,
        EXIT
    } threadStatus;

    typedef void (*fuc_t)(void *);

public:
    myThread(int num, fuc_t fuc, void *args)
        : _tid(0), _status(NEW), _fuc(fuc), _args(args)
    {
        char name[128];
        snprintf(name, 128, "thread-%d ", num);
        _name = name;
    }
    ~myThread()
    {
    }
    std::string threadname()
    {
        return _name;
    }
    pthread_t threadid()
    {
        if(_status==RUNNING)
            return _tid;
        else
        {
            return 0;
        }
    }
    static void *runHelper(void *args)
    {
        myThread *th = static_cast<myThread *>(args);
        th->_fuc(th->_args);
        return nullptr;
    }
    void run()
    {
        int n = pthread_create(&_tid, nullptr, runHelper, this);
        if (n != 0)
        {
            std::cout << "创建线程失败\n";
            exit(1);
        }
        _status = RUNNING;
    }
    void join()
    {
        int n = pthread_join(_tid, nullptr);
        if (n != 0)
        {
            printf("回收线程失败\n");
            exit(2);
        }
        _status = EXIT;
    }

private:
    std::string _name;    // 名字
    pthread_t _tid;       // 线程ID
    threadStatus _status; // 状态
    fuc_t _fuc;           // 回调函数
    void *_args;          //回调函数中的形参

} ;